import { history, type RequestConfig } from "@umijs/max";
import { getToken, removeToken } from "./info";
import { message } from "antd";

const requestInterceptors = [
  (url: string, options: any) => {
    // 把body带上
    const newUrl = `/api${url}`;
    options.headers.Authorization = getToken();
    return {
      url: newUrl,
      options,
    };
  },
];

const responseInterceptors = [
  (response: any) => {
    // 不再需要异步处理读取返回体内容，可直接在data中读出，部分字段可在 config 中找到
    const { data = {} as any } = response;
    const msg = data?.msg || "请求失败";
    if (data.code === "401") {
      //token失效
      removeToken();
      history.push("/login");
      message.error(msg);
      throw msg;
    }
    if (data?.success === false) {
      //请求错误
      message.error(msg);
      throw msg;
    }
    return data;
  },
];

export const request: RequestConfig = {
  timeout: 10000,
  requestInterceptors: requestInterceptors,
  responseInterceptors: responseInterceptors,
};
